﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Icst.Leaflike.Threading
{
    public class ThreadWorker : IRunnable
    {
        public event EventHandler OnTimeout;

        private int _timeout = -1;
        public int Timeout { get { return _timeout; } set { _timeout = (value < -1) ? Math.Abs(value) : value; } }
        public int Interval { get; set; }
        public bool ShouldStop { get; protected set; }
        protected Thread InnerThread { get; set; }

        public ThreadWorker()
        {
            Interval = 1000;
            ShouldStop = false;
            Timeout = -1;
        }
        public virtual void Start() 
        {
            if (InnerThread == null)
                InnerThread = new Thread(OnThread);
            InnerThread.Start(this); 
        }
        protected virtual void OnThread(object state)
        {
            int elapsed = 0;
            //not timeout or not stopped
            while (!ShouldStop || ((Timeout != -1) && (elapsed < Timeout)))
            {
                Run();
                Thread.Sleep(Interval);
                elapsed += Interval;
            }
            if (!ShouldStop && ((Timeout != -1) && (elapsed >= Timeout)))
            {
                if (OnTimeout != null)
                    OnTimeout(this, null);
            }
        }
        public virtual void Stop() { ShouldStop = true; }
        public virtual void Run() { }
    }
}
